<?php
function template_admincp_url(){
    $CI =& get_instance();
    return $CI->config->base_url().'public/templates/admincp/';
}

function admincp_url(){
    $CI =& get_instance();
    return $CI->config->base_url().'admincp/';
}

function template_comingsoon_url(){
    $CI =& get_instance();
    return $CI->config->base_url().'public/comingsoon/';
}

function comingsoon_url(){
    $CI =& get_instance();
    return $CI->config->base_url().'comingsoon/';
}

function template_url(){
    $CI =& get_instance();
    return $CI->config->base_url().'public/templates/home/';
}

function home_url(){
    $CI =& get_instance();
    return $CI->config->base_url().'home/';
}

function pre($arr) {
    echo "<div style=\"border: 1px solid #000000; margin: 10px; font-size: 11px; color: blue; width: auto; clear: both; float: left; display:block; background-color:#F5F5DC\"><pre>";
    print_r($arr);
    echo "</pre></div>";
}

function pre_die($arr) {
    echo "<div style=\"border: 1px solid #000000; margin: 10px; font-size: 11px; color: blue; width: auto; clear: both; float: left; display:block; background-color:#F5F5DC\"><pre>";
    print_r($arr);
    echo "</pre></div>";
    die();
}

if (!function_exists('trans')) {

    function trans($word) {
        $CI = & get_instance();
        $translates = $CI->registry->get('translate');
        $lang_code = $CI->session->userdata('language');
        if(empty($lang_code)){
            $lang_code = 'en';
        }
        $trans = @$translates[$lang_code][$word];
        if ($trans == "") {
            return $word;
        } else {
            return $trans;
        }
    }

}

if (!function_exists('isValidMd5')) {
    function isValidMd5($md5 = '')
    {
        return preg_match('/^[a-f0-9]{32}$/', $md5);
    }
    
}

if (!function_exists('setting')) {

    function setting($col) {
        $CI = & get_instance();
        $CI->load->model('Msetting', 'setting');
        $setting = $CI->setting->get($col);
        if ($setting == $col) {
            echo $col.' in setting empty data';
        } else {
            return $setting[$col];
        }
    }

}

if(!function_exists('convert_utf8')) {
    function convert_utf8($text){
        $text = str_replace('&Agrave;','À',$text);
        $text = str_replace('&Aacute;','Á',$text);
        $text = str_replace('&Acirc;','Â',$text);
        $text = str_replace('&Atilde;','Ã',$text);
        $text = str_replace('&Egrave;','È',$text);
        $text = str_replace('&Eacute;','É',$text);
        $text = str_replace('&Ecirc;','Ê',$text);
        $text = str_replace('&Igrave;','Ì',$text);
        $text = str_replace('&Iacute;','Í',$text);
        $text = str_replace('&ETH;','Đ',$text);
        $text = str_replace('&Ograve;','Ò',$text);
        $text = str_replace('&Oacute;','Ó',$text);
        $text = str_replace('&Ocirc;','Ô',$text);
        $text = str_replace('&Otilde;','Õ',$text);
        $text = str_replace('&Ugrave;','Ù',$text);
        $text = str_replace('&Uacute;','Ú',$text);
        $text = str_replace('&Yacute;','Ý',$text);
        $text = str_replace('&agrave;','à',$text);
        $text = str_replace('&aacute;','á',$text);
        $text = str_replace('&acirc;','â',$text);
        $text = str_replace('&atilde;','ã',$text);
        $text = str_replace('&egrave;','è',$text);
        $text = str_replace('&eacute;','é',$text);
        $text = str_replace('&ecirc;','ẽ',$text);
        $text = str_replace('&igrave;','ì',$text);
        $text = str_replace('&iacute;','í',$text);
        $text = str_replace('&ograve;','ò',$text);
        $text = str_replace('&oacute;','ó',$text);
        $text = str_replace('&ocirc;','ô',$text);
        $text = str_replace('&otilde;','õ',$text);
        $text = str_replace('&ugrave;','ù',$text);
        $text = str_replace('&uacute;','ú',$text);
        $text = str_replace('&yacute;','ý',$text);
        return $text;
    }   
}

if (!function_exists('create_directory')) {

    function create_directory($path,$name){     
        $path_dir = $path.$name;
        if (!file_exists($path_dir)) {
            mkdir('./'.$path_dir, 0777);
        }else{
            return FALSE;   
        }
    }

}

if (!function_exists('write_log')) {

    function write_log($path = "",$user ="",$data = ""){
        if($user == ""){
            $user = "";
        }
        $f = fopen($path,'a');
        fwrite($f,date("Y-m-d H:i:s").chr(9).$user.chr(9).$data."\r\n");
        fclose($f); 
    }

}

function exit_status($str){
    echo json_encode(array('status'=>$str));
    exit;
}

function get_extension($file_name){
    $ext = explode('.', $file_name);
    $ext = array_pop($ext);
    return strtolower($ext);
}

function generateThumbnail($im_filename,$th_filename,$max_width,$max_height,$quality = 0.75){
    // The original image must exist
    if(is_file($im_filename)){
        // Let's create the directory if needed
        $th_path = dirname($th_filename);
        if(!is_dir($th_path))
            mkdir($th_path, 0777, true);
        // If the thumb does not aleady exists
        if(!is_file($th_filename)){
            // Get Image size info
            list($width_orig, $height_orig, $image_type) = @getimagesize($im_filename);
            if(!$width_orig)
                return 2;
            switch($image_type){
                case 1: $src_im = @imagecreatefromgif($im_filename);    break;
                case 2: $src_im = @imagecreatefromjpeg($im_filename);   break;
                case 3: $src_im = @imagecreatefrompng($im_filename);    break;
            }
            if(!$src_im)
                return 3;
            $aspect_ratio = (float) $height_orig / $width_orig;

            $thumb_height = $max_height;
            $thumb_width = round($thumb_height / $aspect_ratio);
            if($thumb_width > $max_width){
                $thumb_width    = $max_width;
                $thumb_height   = round($thumb_width * $aspect_ratio);
            }

            $width = $thumb_width;
            $height = $thumb_height;

            $dst_img = @imagecreatetruecolor($width, $height);
            if(!$dst_img)
                return 4;
            $success = @imagecopyresampled($dst_img,$src_im,0,0,0,0,$width,$height,$width_orig,$height_orig);
            if(!$success)
                return 4;
            switch ($image_type) {
                case 1: $success = @imagegif($dst_img,$th_filename); break;
                case 2: $success = @imagejpeg($dst_img,$th_filename,intval($quality*100));  break;
                case 3: $success = @imagepng($dst_img,$th_filename,intval($quality*9)); break;
            }
            if(!$success)
                return 4;
        }
        return 0;
    }
    return 1;
}

function get_articles($limit=0){
    $CI =& get_instance();
    $CI->load->model('Marticle');
    return $CI->Marticle->showArticles($limit);
}

function get_ship(){
    $CI =& get_instance();
    $CI->load->model('Mship');
    return $CI->Mship->showShip();
}

function get_images($limit=0){
    $CI =& get_instance();
    $CI->load->model('Mgallery');
    return $CI->Mgallery->showImages($limit);
}

function get_products_vertical($limit=0){
    $CI =& get_instance();
    $CI->load->model('Mproduct');
    return $CI->Mproduct->showProduct($limit);
}

function get_list_product_menu(){
    $CI =& get_instance();
    $CI->load->model('Mproduct');
    return $CI->Mproduct->showListProduct();
}

function save_file_setting($table, $file_name){
    $CI =& get_instance();
    $CI->load->database();
    $data = $CI->db->get($table)->result_array();
    $fp = fopen(APPPATH.'../assets/setting/'.$file_name.'.json', 'w');
    fwrite($fp, json_encode($data));
    fclose($fp);
}

function sort_count_character($a,$b){
    return strlen($b)-strlen($a);
}

function format_date($datetime){
    return date('l jS \of F Y h:i:s A',strtotime($datetime));
}

function replace_column($col){
    if(strpos($col, '.') !== FALSE){
        $col = preg_replace('/^[a-z]+./i', '', $col);
    }
    if(strpos($col, 'as') !== FALSE){
        $col = preg_replace('/^[a-z]+ as /i', '', $col);
    }
    return $col;
}

function add_column_datatable($col, $edit=TRUE,$delete=TRUE,$upload=TRUE){
    $CI =& get_instance();
    $CI->load->library('datatables');
    $controller = $CI->router->fetch_class();
    if($edit){
        $CI->datatables
            ->add_column('edit', '<a href="' . admincp_url() . $controller. '/edit/$1" class="btn btn-default tip" title="Edit"><i class="fa '.$CI->config->item('button_edit').'"></i></a>', $col);
    }
    if($delete){
        $CI->datatables
            ->add_column('delete', '<a href="javascript:void(0)" onclick="confirm_delete($1,"'.$controller.'");" class="btn btn-default tip" title="Delete"><i class="fa '.$CI->config->item('button_delete').'"></i></a>', 'id');
    }
    if($upload){
        $CI->datatables
            ->add_column('upload', '<a href="' . admincp_url() . $controller. '/upload/$1" class="btn btn-default tip" title="Upload"><i class="fa '.$CI->config->item('icon_upload').'"></i></a>', $col);
    }
}

function dateformat_PHP_to_jQuery($php_format)
{
    $SYMBOLS_MATCHING = array(
        // Day
        'd' => 'DD',
        'D' => 'ddd',
        'j' => 'D',
        'l' => 'dddd',
        'N' => 'E',
        'S' => 'do',
        'w' => 'e',
        'z' => 'DDDD',
        // Week
        'W' => 'W',
        // Month
        'F' => 'MMMM',
        'm' => 'MM',
        'M' => 'MMM',
        'n' => 'M',
        't' => '',
        // Year
        'L' => '',
        'o' => '',
        'Y' => 'YYYY',
        'y' => 'YY',
        // Time
        'a' => 'a',
        'A' => 'A',
        'B' => 'SSS',
        'g' => 'h',
        'G' => 'H',
        'h' => 'hh',
        'H' => 'HH',
        'i' => 'mm',
        's' => 'ss',
        'u' => ''
    );
    $jqueryui_format = "";
    $escaping = false;
    for($i = 0; $i < strlen($php_format); $i++)
    {
        $char = $php_format[$i];
        if($char === '\\') // PHP date format escaping character
        {
            $i++;
            if($escaping) $jqueryui_format .= $php_format[$i];
            else $jqueryui_format .= '\'' . $php_format[$i];
            $escaping = true;
        }
        else
        {
            if($escaping) { $jqueryui_format .= "'"; $escaping = false; }
            if(isset($SYMBOLS_MATCHING[$char]))
                $jqueryui_format .= $SYMBOLS_MATCHING[$char];
            else
                $jqueryui_format .= $char;
        }
    }
    return $jqueryui_format;
}